<route>
{
  "meta":{
    "title":"APP设置",
    "showMenu" :true,
    "envHide":"DESINGER,PREVIEW,PORTAL",
    "serialNum": 66,
    "localism": "sys.app_setting"
  }
}
</route>

<template>
  <div>
    <el-row :gutter="12">
      <el-col class="mt10 mb10">
        <el-button type="primary" @click="showUploadModal">{{
          $t("sys.app_upload")
        }}</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData">
      <el-table-column :label="$t('APK')" prop="appName"></el-table-column>
      <el-table-column
        :label="$t('sys.app_version')"
        prop="version"
      ></el-table-column>
      <el-table-column :label="$t('sys.app_status')">
        <template slot-scope="scope">
          <span>{{ scope.row.status | statusFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('sys.creator')"
        prop="createBy"
      ></el-table-column>
      <el-table-column :label="$t('sys.create_time')" prop="createDate">
        <template slot-scope="scope">
          <span>{{ scope.row.createDate | moment }}</span>
        </template></el-table-column
      >
      <el-table-column
        :label="$t('sys.description')"
        prop="description"
      ></el-table-column>

      <el-table-column :label="$t('sys.operation')">
        <template slot-scope="scope">
          <el-button @click="downloadExcelTemplate(scope.row)" type="text">{{
            $t("sys.app_download_file")
          }}</el-button>

          <el-divider direction="vertical" v-if="scope.row.status == 0" />

          <el-popconfirm
            :title="$t('sys.app_confirm_publish')"
            :confirm-button-text="$t('sys.confirm')"
            :cancel-button-text="$t('sys.cancel')"
            @confirm="publish(scope.row)"
          >
            <el-button
              slot="reference"
              v-if="scope.row.status == 0"
              type="text"
              >{{ $t("sys.app_publish") }}</el-button
            >
          </el-popconfirm>
          <el-divider direction="vertical" v-if="scope.row.status != 1" />
          <el-popconfirm
            :title="$t('sys.app_confirm_delete')"
            :confirm-button-text="$t('sys.confirm')"
            :cancel-button-text="$t('sys.cancel')"
            @confirm="handleDelete(scope.row.id)"
          >
            <el-button
              slot="reference"
              v-if="scope.row.status != 1"
              type="text"
              >{{ $t("sys.delete") }}</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- table end -->

    <!-- upload Modal -->
    <el-dialog
      width="520px"
      :title="$t('sys.app_appUpload')"
      :visible="visible"
      @close="handleCancel"
    >
      <el-form ref="form" label-width="80px">
        <el-form-item>
          <span slot="label">
            APP&nbsp;
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('sys.app_name_tipes')"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <el-upload
            :limit="1"
            accept=".apk"
            action="''"
            :file-list="fileList"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :http-request="customRequest"
            :auto-upload="true"
          >
            <el-button :loading="uploading">
              <i class="el-icon-upload2"></i>
              {{ $t("sys.app_upload_file") }}
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('sys.description')">
          <el-input type="textarea" :rows="4" v-model="description"> </el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="handleCancel"> {{ $t("sys.cancel") }} </el-button>
        <el-button
          type="primary"
          :disabled="uploading || noFile"
          :loading="confirmLoading"
          @click="handleUpload"
        >
          {{ $t("sys.app_upload") }}
        </el-button>
        <el-button
          type="primary"
          :disabled="uploading || noFile"
          :loading="confirmLoading"
          @click="handlePublish"
        >
          {{ $t("sys.app_upload_publish") }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBasePath } from "@/config/api.config";
import { downloadFileSrc } from "@/utils/util";
import {
  getApppedestalList,
  postApppedestal,
  deleteApppedestal,
  putApppedestalPublish,
} from "@/apis/paas/HmAppPedestalController";
import { postImagesUpload } from "@/apis/paas/ImagesController";
import i18n from "../../../../i18n";
export default {
  name: "AppSetting",
  filters: {
    statusFormat(value) {
      let formatValue = "";
      switch (value) {
        case 0:
          formatValue = i18n.t("sys.app_status_uploaded");
          break;
        case 1:
          formatValue = i18n.t("sys.app_status_published");
          break;
        case 2:
          formatValue = i18n.t("sys.app_status_disabled");
          break;
        default:
          formatValue = i18n.t("sys.app_status_disabled");
          break;
      }
      return formatValue;
    },
  },
  data() {
    return {
      tableData: [],
      apkUrl: "",
      filename: "",
      description: "",
      visible: false,
      confirmLoading: false,
      uploading: false,
      noFile: true,
      fileList: [],
    };
  },

  created() {
    this.loadData();
  },

  methods: {
    loadData() {
      getApppedestalList({}).then((res) => {
        this.tableData = res;
      });
    },
    clearForm() {
      this.filename = "";
      this.fileList = [];
      this.apkUrl = "";
      this.description = "";
      this.noFile = true;
    },
    /**
     * 删除
     */
    handleDelete(id) {
      deleteApppedestal({
        id: id,
      }).then((res) => {
        this.$message.success(this.$t("sys.operation_success"));
        this.loadData();
      });
    },

    showUploadModal() {
      this.clearForm();
      this.visible = true;
    },
    handleUpload(e) {
      this.confirmLoading = true;
      const params = {
        appName: this.filename,
        filePath: this.apkUrl,
        version: this.returnVersionByFileName(this.filename),
        status: 0,
        description: this.description,
      };
      postApppedestal(params)
        .then((res) => {
          this.visible = false;
          this.clearForm();
          this.$message.success(this.$t("sys.operation_success"));
          this.loadData();
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    handlePublish(e) {
      this.confirmLoading = true;
      const params = {
        appName: this.filename,
        version: this.returnVersionByFileName(this.filename),
        status: 0,
        filePath: this.apkUrl,
        description: this.description,
      };
      postApppedestal(params)
        .then((res) => {
          putApppedestalPublish({
            id: res,
            status: 1,
          })
            .then((res) => {
              this.visible = false;
              this.loadData();
              this.clearForm();
              this.$message.success(this.$t("sys.operation_success"));
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        })
        .finally(() => {
          this.confirmLoading = false;
        });
    },
    handleCancel(e) {
      this.visible = false;
    },

    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.clearForm();
    },
    // 上传文件
    async customRequest({ file }) {
      const formData = new FormData();
      formData.append("file", file);
      try {
        this.uploading = true;
        const res = await postImagesUpload(formData);
        if (!!res) {
          this.apkUrl = res;
          this.filename = file.name;
          this.fileList = [...this.fileList, file];
          this.noFile = false;
        }
      } catch (error) {
        this.noFile = true;
        return Promise.reject();
      } finally {
        this.uploading = false;
      }
    },
    returnVersionByFileName(filename) {
      let endStr = filename.split("_").reverse()[0]?.replace(".apk", "");
      const reg = /^[v]\d+(?:\.\d+){2}/;
      const version = endStr.match(reg)?.[0];
      return version;
    },
    beforeUpload(file) {
      const isCorrectName = !!this.returnVersionByFileName(file.name);
      if (!isCorrectName) {
        this.$message.error(this.$t("sys.app_file_name_error"));
      }
      return isCorrectName;
    },
    async downloadExcelTemplate({ appName, filePath }) {
      downloadFileSrc(getBasePath(filePath), appName);
    },
    publish({ id }) {
      putApppedestalPublish({
        id: id,
        status: 1,
      }).then((res) => {
        this.$message.success(this.$t("sys.operation_success"));
        this.loadData();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding: 20px 20px 10px !important;
}
::v-deep .el-dialog__body {
  padding: 25px 30px 30px !important;
}
</style>
